;(function () {
  new Vue({
    el:'#template-add',
    data:{
      templateId:null,
      isShowSysLayer:false,
      isShowTxtLayer:false,
      isShowFontLayer:false,
      systemContent:[{'eleName':null,'eleType':null,'eleValue':null,'checked':true,'zdyName':null,'zdyNameFlag':false}],
      tmpText:null,
      name:null,
      pageLeft:null,
      pageRight:null,
      pageTop:null,
      pageBottom:null,
      imageMes:[],
      head:[],
      footer:[],
      systemPopType:'header',
      selectedFontSize:'14',
      selectedBlockItem:null,
      fontSizeName:'项目名称',
      tbTitle:[
        // {'eleName':'费项','eleDispName':null,'eleShow':'Y','editFlag':false, sort: 0},
        // {'eleName':'付款截止时间','eleDispName':null,'eleShow':'Y','editFlag':false, sort: 1},
        // {'eleName':'记账周期','eleDispName':null,'eleShow':'Y','editFlag':false, sort: 2},
        // {'eleName':'单价','eleDispName':null,'eleShow':'Y','editFlag':false, sort: 3},
        // {'eleName':'日单价','eleDispName':null,'eleShow':'Y','editFlag':false, sort: 4},
        // {'eleName':'月单价','eleDispName':null,'eleShow':'N','editFlag':false, sort: 5},
        // {'eleName':'用量','eleDispName':null,'eleShow':'Y','editFlag':false, sort: 6},
        // {'eleName':'总价','eleDispName':null,'eleShow':'Y','editFlag':false, sort: 7},
        // {'eleName':'已付','eleDispName':null,'eleShow':'N','editFlag':false, sort: 8},
        // {'eleName':'应收','eleDispName':null,'eleShow':'N','editFlag':false, sort: 9},
      ],
      tbContent:[
        {'value':'租金','eleShow':'Y'},
        {'value':'2018-06-26','eleShow':'Y'},
        {'value':'2018-06-26 至 2018-09-26','eleShow':'Y'},
        {'value':'3元／平米／天','eleShow':'Y'},
        {'value':'3元／天','eleShow':'Y'},
        {'value':'3元／月','eleShow':'N'},
        {'value':'500','eleShow':'Y'},
        {'value':'12,000.00元','eleShow':'Y'},
        {'value':'13,000.00元','eleShow':'Y'},
        {'value':'12,000.00元','eleShow':'Y'},
        {'value':'12,000.00元','eleShow':'N'},
        {'value':'12,000.00元','eleShow':'N'},
      ],
      fontSizeProList:[],
      fontSizeList:[
        {'name':'12号','code':'12'},
        {'name':'14号','code':'14'},
        {'name':'16号','code':'16'},
        {'name':'18号','code':'18'},
      ]
    },
    filters:{
      formatUndefined: function(item) {
        if (!item && item != 0) return '--'
        return item
      }
    },
    methods:{
      getData(){
        var self = this;
        var data = window.sessionStorage.getItem('tmpCacheData') ? JSON.parse(window.sessionStorage.getItem('tmpCacheData')) : null;
        // 如果本地缓存有新增的模版数据，则需要展示出模版数据
        if(data) showTemplateMes(data)

        function showTemplateMes(data){
          // 名字和页边距
          self.templateId = data.id;
          self.name = data.name;
          self.pageLeft = data.page[0] ? data.page[0].eleMarginLeft : '0';
          self.pageRight = data.page[0] ? data.page[0].eleMarginRight : '0';
          self.pageTop = data.page[0] ? data.page[0].eleMarginTop : '0';
          self.pageBottom = data.page[0] ? data.page[0].eleMarginBottom : '0';
          self.imageMes = data.image == '#' ? [] : data.image

          // 页面头部
          var head = [],footer = [];
          if(data.head.length && data.head != '#'){
            data.head.forEach((el,i) => {
              head.push({
                'eleType':el.eleType,
                'eleName':el.eleName,
                'eleDispName':el.eleDispName ? el.eleDispName : el.eleName,
                'eleValue':el.eleValue,
                'editFlag':false,
                'eleSize':el.eleSize ? el.eleSize : '14',
                'eleId':el.eleId ? el.eleId : '#',
                'sort': el.sort
              })
            })
          }
          self.head = head;
          // 页面尾部
          if(data.tail.length && data.tail != '#'){
            data.tail.forEach((el,i) => {
              footer.push({
                'eleType':el.eleType,
                'eleName':el.eleName,
                'eleDispName':el.eleDispName ? el.eleDispName : el.eleName,
                'eleValue':el.eleValue,
                'editFlag':false,
                'eleSize':el.eleSize ? el.eleSize : '14',
                'eleId':el.eleId ? el.eleId : '#',
                'sort': el.sort
              })
            })
          }
          self.footer = footer;
          // 页面内容区
          var tbTitle = [],tbContent = [];
          data.content.forEach((el,i) => {
            tbTitle.push({
              'eleId':el.eleId,
              'eleName':el.eleName,
              'eleDispName':el.eleDispName ? el.eleDispName : null,
              'eleShow':el.eleShow,
              'editFlag':false,
              'sort': el.sort
            })
          })
          self.tbTitle = tbTitle
        }
      },
      getSystemConfigItem(){
        var self = this;
        hlhttp.get({
          url:'bill/print_template_sys',
          success:function(data){
            var sysTypeData = [], colTypeData = []
            data.forEach((el,i) => {
              let tmpObj = {}
              if(el.eleType == 'sys'){
                tmpObj = Object.assign({'checked':false,'zdyName':null,'zdyNameFlag':false},el)
                sysTypeData.push(tmpObj)
              }

              if(el.eleType == 'col'){
                tmpObj = Object.assign({'eleDispName':null,'sort':el.eleOrder,'editFlag':false},el)
                colTypeData.push(tmpObj)
              }

            })

            self.systemContent = sysTypeData;
            self.tbTitle = colTypeData;

            console.log(colTypeData);
          }
        })
      },
      selectSystemItem(i){
        var self = this;
        if(self.systemContent[i]['checked'] == true){
          self.systemContent[i]['checked'] = false;
        }else{
          self.systemContent[i]['checked'] = true;
        }
      },
      editSystemItemName(i){
        var self = this;
        if(self.systemContent[i]['zdyNameFlag'] == true){
          self.systemContent[i]['zdyNameFlag'] = false;
        }else{
          self.systemContent[i]['zdyNameFlag'] = true;
        }
      },
      saveSystemItemName(i){
        var self = this;
        self.systemContent[i]['zdyNameFlag'] = false;
      },

      editHeadLabelName(i){
        this.head[i]['editFlag'] = true;
      },
      editFooterLabelName(i){
        this.footer[i]['editFlag'] = true;
      },

      saveHeadName(i){
        this.head[i]['editFlag'] = false;
      },
      saveFooterName(i){
        this.footer[i]['editFlag'] = false;
      },

      deleteHeadLabelItem(i){
        this.head.splice(i,1);
      },
      deleteFooterLabelItem(i){
        this.footer.splice(i,1);
      },

      addHeadBlockItemBtn(){
        var self = this;
        var tmpObj = {
          'eleType':'ph',
          'editFlag':true
        }
        self.head.push(tmpObj)
      },
      addFooterBlockItemBtn(){
        var self = this;
        var tmpObj = {
          'eleType':'ph',
          'editFlag':true
        }
        self.footer.push(tmpObj)
      },

      addHeadTextItemBtn(){
        this.isShowTxtLayer = true;
        this.systemPopType = 'head'
      },
      addFooterTextItemBtn(){
        this.isShowTxtLayer = true;
        this.systemPopType = 'footer'
      },

      clearHead(){
        var self = this;
        hllayer.confirm1('此操作不可逆，确定清空吗？', function() {
            self.head = [];
        })
      },
      clearFooter(){
        var self = this;
        hllayer.confirm1('此操作不可逆，确定清空吗？', function() {
            self.footer = [];
        })
      },

      addSystemItemBtn(type){
        this.systemPopType = type;
        this.isShowSysLayer = true;
      },
      resetSystemItem(){
        this.systemContent.forEach((el,i) => {
          this.systemContent[i]['checked'] = false;
          this.systemContent[i]['zdyNameFlag'] = false;
          this.systemContent[i]['zdyName'] = null;
        })
      },
      confirmAddSysItem(){
        // 添加的系统内容 根据 sysType 字段区分是 txt类型和date类型
        // 通过系统内容中 checked === true 的项 为添加项
        let arr = [];
        this.systemContent.forEach((el,i) => {
          if(el.checked == true){
            arr.push({
              'eleType':el.eleType,
              'eleName':el.eleName,
              'eleDispName':el.zdyName ? el.zdyName : el.eleName,
              'eleValue':el.eleValue,
              'editFlag':false,
              'eleSize':'14',
              'sort': el.sort
            })
          }
        })

        if(this.systemPopType == 'head') this.head = this.head.concat(arr);
        if(this.systemPopType  == 'footer') this.footer = this.footer.concat(arr);
        this.resetSystemItem()
        this.isShowSysLayer = false;
      },
      closeSysLayer(){
        this.resetSystemItem()
        this.isShowSysLayer = false;
      },

      confirmAddTxtItem(){
        var self = this;
        var tmpObj = {
          'eleType':'txt',
          'editFlag':false,
          'eleValue':self.tmpText,
          'eleSize':'14'
        }
        if(self.systemPopType == 'head') self.head.push(tmpObj)
        if(self.systemPopType == 'footer') self.footer.push(tmpObj)
        this.tmpText = null;
        this.isShowTxtLayer = false;
      },

      closeTxtLayer(){
        this.tmpText = null;
        this.isShowTxtLayer = false;
      },

      editBillName(val,i){
        if(val == 'Y'){
          this.tbTitle[i]['editFlag'] = true;
        }
      },

      saveBillName(i){
        this.tbTitle[i]['editFlag'] = false;
      },

      changeBillTableColumn(val,i){
        if(val == 'Y')  this.tbTitle[i]['eleShow'] = 'N'
        if(val == 'N')  this.tbTitle[i]['eleShow'] = 'Y'
        if(val == 'Y')  this.tbContent[i]['eleShow'] = 'N'
        if(val == 'N')  this.tbContent[i]['eleShow'] = 'Y'
      },

      addFontSize(val){
        this.systemPopType = val;
        this.selectedFontSize = '14';
        this.isShowFontLayer = true;
        this.fontSizeName = '项目名称';
        // 整理要调整字体大小的项
        let tmpArr = [];
        if(val == 'head'){
          this.head.forEach((el,i) => {
            tmpArr.push({'eleType':el.eleType,'eleDispName':el.eleDispName,'eleValue':el.eleValue})
          })
        }
        if(val == 'footer'){
          this.footer.forEach((el,i) => {
            tmpArr.push({'eleType':el.eleType,'eleDispName':el.eleDispName,'eleValue':el.eleValue})
          })
        }
        this.fontSizeProList = tmpArr;
      },

      selectBlockItem(type,dispName,value){
        if(type == 'txt') this.selectedBlockItem = value;
        if(type == 'sys') this.selectedBlockItem = dispName;
      },

      selectFontSize(code){
        this.selectedFontSize = code;
      },

      confirmAddFontItem(){
        const changeHeadBlockFontSize = () => {
          this.head.forEach((el,i) => {
            if( el.eleDispName == this.selectedBlockItem || el.eleValue == this.selectedBlockItem ) this.head[i]['eleSize'] = this.selectedFontSize
          })
        }
        const changeFooterBlockFontSize = () => {
          this.footer.forEach((el,i) => {
            if( el.eleDispName == this.selectedBlockItem || el.eleValue == this.selectedBlockItem ) this.footer[i]['eleSize'] = this.selectedFontSize
          })
        }

        if(this.systemPopType == 'head') changeHeadBlockFontSize()
        if(this.systemPopType == 'footer') changeFooterBlockFontSize()
        this.isShowFontLayer = false;
      },
      closeFontLayer(){
        this.isShowFontLayer = false;
      },

      validate(){
        var self = this;
        if(!self.name){
          hl.toast('模板名称不能为空！')
          $('.module-name').focus()
          return false;
        }
        return true;
      },

      dealSubmitData(){
        var self = this;
        // 获取定位
        const getPosition = (index) => {
          const i = index % 3
          let res;
          switch (i) {
            case 0:
              res = 'TL'
              break;
            case 1:
              res = 'TC'
              break;
            case 2:
              res = 'TR'
              break;
            default:
          }
          return res;
        }

        // 页边距信息
        var pageBlock = [];
        const pagePadding = {
          'ele_name':'#',
          'ele_disp_name':'#',
          'ele_type':'page',
          'ele_margin_left':self.pageLeft ? self.pageLeft : '#',
          'ele_margin_right':self.pageRight ? self.pageRight : '#',
          'ele_margin_top':self.pageTop ? self.pageTop : '#',
          'ele_margin_bottom':self.pageBottom ? self.pageBottom : '#',
          'ele_block':'page',
          'ele_value':'#',
          'ele_position':'#',
          'ele_height':'#',
          'ele_width':'#',
          'ele_size':'#',
          'ele_metric':'px',
          'ele_opacity':'#',
          'ele_order':'#',
          'ele_show':'#'
        }
        pageBlock.push(pagePadding)
        // 头部内容
        const headBlock = []
        self.head.forEach((el,i) => {
          var obj = {
            'ele_name':el.eleName ? el.eleName : '#',
            'ele_disp_name':el.eleDispName ? el.eleDispName :'#',
            'ele_type':el.eleType,
            'ele_margin_left':'#',
            'ele_margin_right':'#',
            'ele_margin_top':'#',
            'ele_margin_bottom':'#',
            'ele_value':el.eleValue,
            'ele_block':'head',
            'ele_position': getPosition(i),
            'ele_height':'#',
            'ele_width':'#',
            'ele_size': el.eleSize,
            'ele_metric':'px',
            'ele_opacity':'#',
            "ele_order": i + 1 + '',
            'ele_show':'#',
            'ele_order': el.sort
          }
          headBlock.push(obj)
        })

        // 底部内容
        const footerBlock = []
        self.footer.forEach((el,i) => {
          var obj = {
            'ele_name':el.eleName ? el.eleName : '#',
            'ele_disp_name':el.eleDispName ? el.eleDispName :'#',
            'ele_type':el.eleType,
            'ele_margin_left':'#',
            'ele_margin_right':'#',
            'ele_margin_top':'#',
            'ele_margin_bottom':'#',
            'ele_value':el.eleValue,
            'ele_block':'tail',
            'ele_position': getPosition(i),
            'ele_height':'#',
            'ele_width':'#',
            'ele_size': el.eleSize,
            'ele_metric':'px',
            'ele_opacity':'#',
            "ele_order": i + 1 + '',
            'ele_show':'#',
            'ele_order': i
          }
          footerBlock.push(obj)
        })

        // 中间图表内容区
        const contentBlock = []
        self.tbTitle.forEach((el,i) => {
          var obj = {
            'ele_type':'col',
            'ele_name':el.eleName,
            'ele_disp_name':el.eleDispName ? el.eleDispName : '#',
            'ele_block':'content',
            'ele_show':el.eleShow,
            'ele_order': el.eleOrder,
            'ele_value':el.eleValue
          }
          contentBlock.push(obj)
        })

        return submitData = {
          'name':self.name,
          'page':JSON.stringify(pageBlock),
          'image':'#',
          'head':headBlock.length == 0 ? '#' : JSON.stringify(headBlock),
          'content':JSON.stringify(contentBlock),
          'tail':footerBlock.length == 0 ? '#' : JSON.stringify(footerBlock)
        }
      },

      sendSaveTmpRequest(cb){
        var self = this;
        var submitData = self.dealSubmitData();
        var valid = self.validate();

        if(valid){
          hlhttp.post({
            url:'bill/print_template',
            data:{'print_template':JSON.stringify(submitData)},
            success:function(data){
              if(cb) cb(data)
            }
          })
        }
      },

      saveTmp(cb){
        this.sendSaveTmpRequest((data) => {
          this.templateId = data.templateId;
          hl.toast('模版保存成功');
          hlUrlUtil.goTo('templateConfig',{ddtab:true},false)
        })
      },

      previewTmp(){
        // 缓存数据到本地
        var self = this;
        // 获取定位
        const getPosition = (index) => {
          const i = index % 3
          let res;
          switch (i) {
            case 0:
              res = 'TL'
              break;
            case 1:
              res = 'TC'
              break;
            case 2:
              res = 'TR'
              break;
            default:
          }
          return res;
        }

        // 页边距信息
        var pageBlock = [];
        const pagePadding = {
          'eleType':'page',
          'eleMarginLeft':self.pageLeft ? self.pageLeft : '0',
          'eleMarginRight':self.pageRight ? self.pageRight : '0',
          'eleMarginTop':self.pageTop ? self.pageTop : '0',
          'eleMarginBottom':self.pageBottom ? self.pageBottom : '0',
          'eleBlock':'page',
          'eleMetric':'px'
        }
        pageBlock.push(pagePadding)
        // 头部内容
        const headBlock = []
        self.head.forEach((el,i) => {
          var obj = {
            'eleName':el.eleName ? el.eleName : '',
            'eleDispName':el.eleDispName ? el.eleDispName :'',
            'eleType':el.eleType,
            'eleValue':el.eleValue,
            'eleBlock':'head',
            'elePosition': getPosition(i),
            'eleSize': el.eleSize,
            'eleMetric':'px',
            "eleOrder": i + 1 + '',
          }
          headBlock.push(obj)
        })

        // 底部内容
        const footerBlock = []
        self.footer.forEach((el,i) => {
          var obj = {
            'eleName':el.eleName ? el.eleName : '',
            'eleDispName':el.eleDispName ? el.eleDispName :'',
            'eleType':el.eleType,
            'eleValue':el.eleValue,
            'eleBlock':'tail',
            'elePosition': getPosition(i),
            'eleSize': el.eleSize,
            'eleMetric':'px',
            "eleOrder": i + 1 + ''
          }
          footerBlock.push(obj)
        })

        // 中间图表内容区
        const contentBlock = []
        self.tbTitle.forEach((el,i) => {
          var obj = {
            'eleType':'col',
            'eleName':el.eleName,
            'eleDispName':el.eleDispName ? el.eleDispName : '',
            'eleBlock':'content',
            'eleShow':el.eleShow
          }
          contentBlock.push(obj)
        })

        // image
        var imageBlock = [];
        if(self.imageMes.length){
          self.imageMes.forEach((el,i) => {
            const obj = {
              'ele_name':'#',
              'ele_disp_name':'#',
              'ele_type':'img',
              'ele_margin_left':el.eleMarginLeft ? el.eleMarginLeft : '#',
              'ele_margin_right':el.eleMarginRight ? el.eleMarginRight : '#',
              'ele_margin_top':el.eleMarginTop ? el.eleMarginTop : '#',
              'ele_margin_bottom':el.eleMarginBottom ? el.eleMarginBottom : '#',
              'ele_block':'image',
              'ele_value':el.eleValue,
              'ele_position':'#',
              'ele_height':el.eleHeight,
              'ele_width':el.eleWidth,
              'ele_size':'#',
              'ele_metric':'px',
              'ele_opacity':el.eleOpacity,
              'ele_order':'#',
              'ele_show':'#'
            }
            imageBlock.push(obj)
          })
        }

        const cacheData = {
          'name':self.name,
          'page':pageBlock,
          'image':imageBlock.length == 0 ? '#' : JSON.stringify(imageBlock),
          'head':headBlock.length == 0 ? '#' : headBlock,
          'content':contentBlock,
          'tail':footerBlock.length == 0 ? '#' : footerBlock
        }

        window.sessionStorage.setItem('tmpCacheData',JSON.stringify(cacheData))
        hlUrlUtil.goTo('templateAddPreview',{ddtab:true})
      }
    },
    created:function(){
      this.getData()
    },
    mounted:function () {
      hlSelectUi(true)
      this.getSystemConfigItem()
    }
  })
}())
